clear all;
close all;
clc
All_Mu=[11 10 11 11 11 10 10 11 13 8 11 11 12 10 11 10]
Subjects = {'A63','A64','A68','A69','A70','A72','A73','A74','A75','A76','A77','A78','A79','A80','A81','A82'};
Channels = 1:31;
hiddenlayers = 15;

Kfold = 10;
fs = 500;
dt = 1/fs;
f_Conditions_EMG_EEG_up
finger_names = {'Thumb';'Index';'Middle';'Ring';'Pinky'};
fingers = 'abcde';
pcolor = 'kbr';
Pre = 0; % on
dur = 3.5; % off
tsig_ori=Pre+dt:dt:dur;
NN = length(tsig_ori);
plot_triggers = 0;
% ifnumber = 1;
% kernal = 5;
% Ntrials = 50;
% N_points = 200;
for isub = 1:length(Subjects)
    Sub = Subjects{isub};
    Mu = All_Mu(isub);
    [b,a]=fir1(100,[30 50]./(fs/2));
    eval(['condall=' Sub '_all;']);
    % outcor = f_heatmap_subplot(4,4);
    for ifinger = 1:5
        EEG_and_EMG{ifinger}= [];
    end
    Nsession  = zeros(1,5);
    for ii = 1:N_column:length(condall)
        % for isession = 1:N_column:200
        chunkline = {condall{ii:ii+N_column-1}};
        if mod(ii,80)==1
            chunkline
        end
        finger = chunkline{1}(end);
        ifinger = find(fingers==finger);
        Nsession(ifinger)=Nsession(ifinger)+1;
        fname = ['EEG_data\' chunkline{2} ];
        eval(['load ' fname(1:end-4) '_P']);
        new_data2=f_montage(new_data);
        for jc_channel = Channels
            xdata = conv(new_data2(jc_channel,:),b,'same');
            new_data3(jc_channel,:)=xdata;
            p_all(jc_channel) = mean(new_data2(jc_channel,:).^2);
        end
        for i = 1:length(newTR_time) %  all triggers
            Ttime = newTR_time(i);
            [YY Ind] = min(abs(Ttime-tsig_long));
            for jc_channel = Channels
                chunk = new_data3(jc_channel,Ind+round((1+Pre)*fs):Ind+round((1+Pre)*fs)+NN-1);
                % power(i,jc_channel) = mean(chunk.^2);
                power(i,jc_channel) = mean(chunk.^2)./ p_all(jc_channel);

            end
        end
        clear new_data3;
        pause(0.1)
        %=========== now, EMG:
        filename = ['Save_RMS_up\' Sub(2:end) '_' num2str(Nsession(ifinger)) fingers(ifinger) '.mat']; %read or import
        load(filename);
        hemg = EMG_rms';
        EEG_and_EMG{ifinger}=[EEG_and_EMG{ifinger}
            power hemg];
        clear power
    end % isession
    Xall = [];
    for i=1:5
        Xall=[
            Xall
            EEG_and_EMG{i} ];
    end
    grand_avg = mean(Xall);
    for i=1:5
        All_vectors{i}=EEG_and_EMG{i}-grand_avg;
    end
    out=f_runNN_Kfold(hiddenlayers,All_vectors,Kfold);
    %     out = f_SNN_single(All_vectors)
    % out.PC = 0;
    % out.CM = 0;

    PC_all(isub)=out.PC
    CM_all{isub}=out.CM;
    clear EEG_and_EMG
    pause(0.1)
    % pause
end % isub
figure
bar(PC_all)
% exportgraphics(f1,['EEG_81.png'],'Resolution',300);
save pc_EEGEMGcombined_15layers PC_all CM_all

ylim([0 1])
